package com.macrohard.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.macrohard.admin.service.SysMenuService;
import com.macrohard.admin.service.SysRelationService;
import com.macrohard.mapper.domain.SysMenu;
import com.macrohard.mapper.domain.SysRelation;
import com.macrohard.mapper.mapper.SysRelationMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

/**
* @author 27371
* @description 针对表【sys_relation】的数据库操作Service实现
* @createDate 2022-07-14 12:32:00
*/
@Service
@RequiredArgsConstructor
public class SysRelationServiceImpl extends ServiceImpl<SysRelationMapper, SysRelation>
    implements SysRelationService {
	private final SysMenuService menuService;

	@Override
	public boolean updateByMenuIds(Integer tId, List<Integer> ids) {
		List<Integer> onceOwned = menuService.getMenuWithTeacherRole(tId, true).stream().map(SysMenu::getId).collect(Collectors.toList());
		List<Integer> allIds = menuService.list().stream().map(SysMenu::getId).collect(Collectors.toList());
		HashSet<Integer> onceOwnedSet = new HashSet<>(onceOwned);
		HashSet<Integer> nowOwnedSet = new HashSet<>(ids);
		AtomicBoolean res = new AtomicBoolean(true);
		allIds.forEach(id -> {
			// 删除
			if (!nowOwnedSet.contains(id) && onceOwnedSet.contains(id)) {
				LambdaQueryWrapper<SysRelation> queryWrapper = new LambdaQueryWrapper<>();
				queryWrapper.eq(SysRelation::getTid, tId)
								.eq(SysRelation::getMid, id);
				boolean remove = remove(queryWrapper);
				if (!remove) {
					res.set(false);
				}
			}
			// 添加
			if (nowOwnedSet.contains(id) && !onceOwnedSet.contains(id)) {
				SysRelation relation = new SysRelation();
				relation.setTid(tId);
				relation.setMid(id);
				boolean save = save(relation);
				if (!save) {
					res.set(false);
				}
			}
		});
		return res.get();
	}
}




